package hello

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/hex"
	json2 "encoding/json"
	"fmt"
	"gf-app/app/lib/page_lib"
	"gf-app/app/lib/resp"
	"gf-app/app/model/user"
	"github.com/gogf/gf/container/gmap"
	"github.com/gogf/gf/container/gqueue"
	"github.com/gogf/gf/container/gtype"
	"github.com/gogf/gf/crypto/gmd5"
	"github.com/gogf/gf/database/gdb"
	"github.com/gogf/gf/encoding/gbase64"
	"github.com/gogf/gf/encoding/gjson"
	"github.com/gogf/gf/encoding/gparser"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/os/gfile"
	"github.com/gogf/gf/os/glog"
	"github.com/gogf/gf/os/gmutex"
	"github.com/gogf/gf/os/gproc"
	"github.com/gogf/gf/os/grpool"
	"github.com/gogf/gf/os/gtime"
	"github.com/gogf/gf/os/gtimer"
	"github.com/gogf/gf/text/gstr"
	"github.com/gogf/gf/util/gconv"
	"github.com/gogf/gf/util/grand"
	"github.com/gogf/gf/util/gutil"
	"github.com/gogf/gf/util/guuid"
	"github.com/gogf/gf/util/gvalid"
	"os"
	"time"
)

type Test struct {
}

// Hello World
func Handler(r *ghttp.Request) {
	//127.0.0.1:8199/?amount=19.66
	r.Response.Writeln(r.Get("amount"))
	r.Response.Writeln(r.GetInt("amount"))
	r.Response.Writeln(r.GetFloat32("amount"))

	//http://127.0.0.1:8199/?map[id]=1&map[name]=john
	r.Response.Writeln(r.Get("map"))
	r.Response.Writeln("Hello World!")
}

func (o *Test) Hello(r *ghttp.Request) {
	r.Response.WriteJsonExit("test.hello")
}

func (o *Test) Index(r *ghttp.Request) {
	r.Response.WriteJsonExit("test.index")
}

//构造函数
func (o *Test) Init(r *ghttp.Request) {
	fmt.Println("test.init")
}

//析构函数
func (o *Test) Shut(r *ghttp.Request) {
	fmt.Println("test.shut")
}

type RegisterReq struct {
	Name  string `p:"username" v:"required|length:6,30#请输入账号|账号长度为:min到:max位"`
	Pass  string `p:"password1" v:"required|length:6,30#请输入密码|密码长度不够"`
	Pass2 string `p:"password2" v:"required|length:6,30|same:password1#请确认密码|两次密码不一致"`
}

type RegisterRes struct {
	Code  int         `json:"code"`
	Error string      `json:"error"`
	Data  interface{} `json:"data"`
}

func TestParams(r *ghttp.Request) {
	var req *RegisterReq
	//127.0.0.1:8199/admin/testParams?_token=123456&name=jasdasdu&password1=123456&password2=123456
	if err := r.Parse(&req); err != nil {
		if v, ok := err.(*gvalid.Error); ok {
			//只返回第一个错
			r.Response.WriteJsonExit(RegisterRes{
				Code:  0,
				Error: v.FirstString(),
			})
		}

		r.Response.WriteJsonExit(RegisterRes{
			Code:  0,
			Error: err.Error(),
		})
	}
	r.Response.WriteJsonExit(RegisterRes{
		Code: 1,
		Data: req,
	})
}

func TestCookie(r *ghttp.Request) {
	r.Cookie.Set("datetime", gtime.Datetime())
	r.Response.WriteExit(gtime.Datetime())
}

//127.0.0.1:8199/admin/session/set?_token=123456
func SetSession(r *ghttp.Request) {
	r.Session.Set("time", gtime.Timestamp())
	r.Session.Set("a", "b")
	fmt.Println(r.Session.Id())
	r.Response.WriteExit(gtime.Timestamp())
}

//127.0.0.1:8199/admin/session/get?_token=123456
func GetSession(r *ghttp.Request) {
	r.Response.WriteExit(r.Session.Map())
}

func DelSession(r *ghttp.Request) {
	r.Session.Clear()
	r.Response.Write("ok")
}

func TestRequest(r *ghttp.Request) {
	cli := ghttp.NewClient()
	cli.SetCookie("oa_session", "eyJpdiI6ImFwSG5BZnJjc1NhajRNak1zbnhrQ0E9PSIsInZhbHVlIjoickVmMlF1SXV5dGtKUTRSUGpZbkUyQzR6UmVjY0ZXODdOS1VmQjllVXlFR0E5SHFVRHFCdFFmRkR1Zmd6OWFpVCt3eThhWStZU091T1p6M1kyTmVXQ0E9PSIsIm1hYyI6Ijc5ZWYwZDQ1YTA4OGJmNWRjMGE4ZjNjYmNkOWQwYzE2YmZlY2JiMjFjYzc3MmQ2MWRkNDAxNTc4OWEyNDZmY2YifQ%3D%3D")

	//proxy:= func(_ *http.Request) (*url.URL, error){
	//	return url.Parse("http://192.168.90.252:8888")
	//}
	//transport := &http.Transport{Proxy: proxy}
	//cli.SetHeader("Transport", "http://192.168.90.252:8888")

	cliRes, err := cli.Get("http://192.168.90.206/menu/my_workflow")
	defer cliRes.Close()
	if err != nil {
		fmt.Println(err)
	}
	resStr := cliRes.ReadAllString()
	fmt.Println(resStr)
	r.Response.WriteExit(resStr)
}

func GetConfig(r *ghttp.Request) {
	conf := g.Cfg().Get("server.AccessLogEnabled")
	r.Response.WriteJsonExit(conf)
}

func TestLog(r *ghttp.Request) {
	log := glog.New()
	log.Info("test log")

	glog.Println("Printlb日志内容")
	glog.Info("info日志内容")
	glog.Debug("debug日志内容")
	//打印日志的行信息
	glog.Line(true).Info("foo")
	//输出json格式的
	glog.Debug(g.Map{"uid": 100, "name": "allen"})

	logPath := g.Cfg().Get("logger.path")
	fmt.Println(logPath)
	logFile, _ := gfile.ScanDir(logPath.(string), "*")
	g.Dump(logFile)
}

func TestTrace(r *ghttp.Request) {
	//示例1，通过错误方法触发
	//glog.Error("this is error")

	//示例2，通过Stack方法打印
	//glog.PrintStack()
	//glog.New().PrintStack()
}

func DataCheck(r *ghttp.Request) {
	//单数据校验
	rule := "length:6,16"
	if e := gvalid.Check("123456", rule, nil); e != nil {
		fmt.Println(e.String())
	}

	if e := gvalid.Check("12345", rule, nil); e != nil {
		fmt.Println(e.String())
	}

	//
	rule = "integer|between:6,16"
	msgs := "请输入一个整数|参数长度不对啊老铁"
	if e := gvalid.Check(5, rule, msgs); e != nil {
		fmt.Println(e.FirstString())
	}

	//
	rule = "url|min-length:11"
	msgs1 := map[string]string{
		"url":        "请输入正确的URL地址",
		"min-length": "地址长度至少为:min位",
	}
	if e := gvalid.Check("https://goframeorg", rule, msgs1); e != nil {
		fmt.Println(e.Map())
	}

	//多数据校验
	params := map[string]interface{}{
		"passport":  "",
		"password":  "123456",
		"password2": "1234567",
	}
	rules := map[string]string{
		"passport":  "required|length:6,16",
		"password":  "required|length:6,16|same:password2",
		"password2": "required|length:6,16",
	}
	if e := gvalid.CheckMap(params, rules); e != nil {
		fmt.Println(e.Maps())
	}

	//
	params = map[string]interface{}{
		"passport":  "",
		"password":  "123456",
		"password2": "1234567",
	}
	rules = map[string]string{
		"passport":  "required|length:6,16",
		"password":  "required|length:6,16|same:password2",
		"password2": "required|length:6,16",
	}
	msgs2 := map[string]interface{}{
		"passport": "账号不能为空|账号长度应当在:min到:max之间",
		"password": map[string]string{
			"required": "密码不能为空",
			"same":     "两次密码输入不相等",
		},
	}
	if e := gvalid.CheckMap(params, rules, msgs2); e != nil {
		fmt.Println(e.String())
	}

	//
	fmt.Println("======")
	params = map[string]interface{}{
		"passport":  "",
		"password":  "123456",
		"password2": "1234567",
	}
	rules3 := []string{
		"passport@required|length:6,16#账号不能为空|账号长度应当在:min到:max之间",
		"password@required|length:6,16|same:password2#密码不能为空|密码长度应当在:min到:max之间|两次密码输入不相等",
		"password2@required|length:6,16#",
	}
	if e := gvalid.CheckMap(params, rules3); e != nil {
		fmt.Println(e.Map())
		fmt.Println(e.FirstItem())
		fmt.Println(e.FirstString())
	}
	// 输出:
	// map[required:账号不能为空 length:账号长度应当在6到16之间]
	// passport map[required:账号不能为空 length:账号长度应当在6到16之间]
	// 账号不能为空
}

func TestDb(r *ghttp.Request) {
	m := g.DB().Table("user")
	m.Where("id in(?)", g.Slice{1, 2, 3})
	m.Where("id >= ?", 1)
	res, _ := m.All()
	r.Response.WriteJsonExit(res)
}

func TestInsert(r *ghttp.Request) {
	//使用INSERT INTO语句进行数据库写入，如果写入的数据中存在主键或者唯一索引时，返回失败，否则写入一条新数据；
	/*m := g.DB().Table("user")
	_, err := m.Data(g.Map{"name": "john"}).Insert()
	if err != nil {
		fmt.Println(err)
	}
	r.Response.WriteJsonExit("插入成功")*/

	//使用REPLACE INTO语句进行数据库写入，如果写入的数据中存在主键或者唯一索引时，会删除原有的记录，必定会写入一条新记录；
	/*m:=g.DB().Table("user")
	if _,err:=m.Data(g.Map{"id":3,"name":"zhangsan"}).Replace();err!=nil{
		r.Response.WriteJsonExit(err)
	}
	r.Response.WriteJsonExit("插入成功")*/

	//使用INSERT INTO语句进行数据库写入，如果写入的数据中存在主键或者唯一索引时，更新原有数据，否则写入一条新数据；
	/*m:=g.DB().Table("user")
	if _,err:=m.Data(g.Map{"id":4,"name":"allen"}).Save();err!=nil{
		r.Response.WriteJsonExit(err)
	}
	r.Response.Write("插入成功")*/

	//批量插入数据
	db := g.DB().Table("user")
	db.Data(g.List{
		{"name": "ls"},
		{"name": "wu"},
		{"name": "wu"},
	}).Batch(2).Insert()

}

func TestUpdate(r *ghttp.Request) {
	//UPDATE `user` SET `name`='allen yuan' WHERE name='allen'
	g.DB().Table("user").Data(g.Map{"name": "allen yuan"}).Where("name=?", "allen").Update()
	g.DB().Table("user").Data("name='john'").Where("name like ?", "%allen%").Update()

	g.DB().Table("user").Data(g.Map{"name": "zhangsan"}).Order("id desc").Limit(3).Update()
}

func TestDel(r *ghttp.Request) {
	g.DB().Table("user").Where("id > ?", 10).Delete()
	g.DB().Table("user").Order("id desc").Limit(2).Delete()
}

func TestSearch(r *ghttp.Request) {
	//SELECT * FROM `user` WHERE (name ='john') AND (sex = 1)
	res, _ := g.DB().Table("user").Where("name =?", "john").Where("sex = ?", 1).All()
	fmt.Println(res)

	//SELECT * FROM `user` WHERE (name = 'john' and sex = 1) OR (name = 'zs' and sex = 2) ORDER BY `id` desc limit 10
	res1, _ := g.DB().Table("user").Where("name = ? and sex = ?", "john", 1).Or("name = ? and sex = ?", "zs", 2).Order("id desc limit 10").All()
	fmt.Println(res1)

	res2, _ := g.DB().Table("user").Where("id in(?)", g.Slice{1, 2, 3}).Value("name")
	fmt.Println(res2)

	res3, _ := g.DB().Table("user").Value("name", "id in(?)", g.Slice{1, 2, 3})
	fmt.Println(res3)

	res4, _ := g.DB().Table("user").One()
	fmt.Println(res4)

	res5, _ := g.DB().Table("user").Fields("name").All()
	fmt.Println(res5)
	g.Log().Println(res5)
}

func TestDbCache(r *ghttp.Request) {
	db := g.DB("test")

	// 执行2次查询并将查询结果缓存1小时，并可执行缓存名称(可选)
	for i := 0; i < 2; i++ {
		r, _ := db.Table("user").Cache(time.Hour, "vip-user").Where("id", 1).One()
		g.Log().Print(r.Map())
	}

	// 执行更新操作，并清理指定名称的查询缓存
	_, err := db.Table("user").Cache(-1, "vip-user").Data(g.Map{"name": "zhanger"}).Where("id", 1).Update()
	if err != nil {
		g.Log().Print(err)
	}

	r1, _ := db.Table("user").Cache(time.Hour, "vip-user").Where("id", 1).One()
	g.Log().Print(r1)
}

func TestFuncInsert(r *ghttp.Request) {
	db := g.DB()
	db.Insert("user", gdb.Map{
		"name": "nick",
		"sex":  1,
	})
}

func TestFuncSearch(r *ghttp.Request) {
	db := g.DB()
	list, _ := db.GetAll("select * from user limit 2")
	g.Log().Println(list)

	list, _ = db.GetAll("select * from user where id > ? and name like ?", g.Slice{3, "%zhang%"})
	g.Log().Println(list)

	one, _ := db.GetOne("select * from user where name like ? order by id desc limit 2", g.Slice{"%zhang%"})
	g.Log().Println(one)
}

func TestFuncSave(r *ghttp.Request) {
	db := g.DB()
	db.Save("user", gdb.Map{
		"id":   1,
		"name": "mac",
	})

	db.Save("user", gdb.Map{
		"name": "chenqiushi",
	})
}

func TestFuncBatchInsert(r *ghttp.Request) {
	db := g.DB()
	db.BatchInsert("user", gdb.List{
		{"name": "john_1"},
		{"name": "john_2"},
		{"name": "john_3"},
		{"name": "john_4"},
	}, 2)
}

func Testgmap(r *ghttp.Request) {
	// 创建一个默认的gmap对象，
	// 默认情况下该gmap对象不支持并发安全特性，
	// 初始化时可以给定true参数开启并发安全特性。
	m := gmap.New()

	for i := 0; i <= 9; i++ {
		m.Set(i, i)
	}
	//查询大小
	fmt.Println(m.Size())
	//批量设置键值对(不同的数据类型对象参数不同)
	m.Sets(map[interface{}]interface{}{
		10: 10,
		11: 12,
	})
	fmt.Println(m.Size())

	// 查询是否存在
	fmt.Println(m.Contains(1))

	// 查询键值
	fmt.Println(m.Get(1))

	// 删除数据项
	m.Remove(9)
	fmt.Println(m.Size())

	// 批量删除
	m.Removes([]interface{}{10, 11})
	fmt.Println(m.Size())

	// 当前键名列表(随机排序)
	fmt.Println(m.Keys())
	// 当前键值列表(随机排序)
	fmt.Println(m.Values())

	// 查询键名，当键值不存在时，写入给定的默认值
	fmt.Println(m.GetOrSet(100, 100))

	// 删除键值对，并返回对应的键值
	fmt.Println(m.Remove(100))

	// 遍历map
	m.Iterator(func(k interface{}, v interface{}) bool {
		fmt.Printf("%v:%v ", k, v)
		return true
	})

	// 自定义写锁操作
	m.LockFunc(func(m map[interface{}]interface{}) {
		m[99] = 99
	})

	// 自定义读锁操作
	m.RLockFunc(func(m map[interface{}]interface{}) {
		fmt.Println(m[99])
	})

	// 清空map
	m.Clear()

	// 判断map是否为空
	fmt.Println(m.IsEmpty())
}

func TestGmapIterator(r *ghttp.Request) {
	array := g.Slice{2, 3, 1, 5, 4, 6, 8, 7, 9}
	hashMap := gmap.New(true)
	listMap := gmap.NewListMap(true)
	treeMap := gmap.NewTreeMap(gutil.ComparatorInt, true)
	for _, v := range array {
		hashMap.Set(v, v)
	}
	for _, v := range array {
		listMap.Set(v, v)
	}
	for _, v := range array {
		treeMap.Set(v, v)
	}
	fmt.Println("HashMap   Keys:", hashMap.Keys())
	fmt.Println("HashMap Values:", hashMap.Values())
	fmt.Println("ListMap   Keys:", listMap.Keys())
	fmt.Println("ListMap Values:", listMap.Values())
	fmt.Println("TreeMap   Keys:", treeMap.Keys())
	fmt.Println("TreeMap Values:", treeMap.Values())
}

func Testgval(r *ghttp.Request) {
	var v g.Var

	v.Set("123")

	fmt.Println(v.Val())

	// 基本类型转换
	fmt.Println(v.Int())
	fmt.Println(v.Uint())
	fmt.Println(v.Float64())

	// slice转换
	fmt.Println(v.Ints())
	fmt.Println(v.Floats())
	fmt.Println(v.Strings())

	// struct转换
	type Score struct {
		Value int
	}
	s := new(Score)
	v.Struct(s)
	fmt.Println(s)

}

func TestGtype(r *ghttp.Request) {
	i := gtype.NewInt(10)
	fmt.Println(i.Val())
	i.Set(9)
	i.Add(-1)
	fmt.Println(i.Val())

	type Student struct {
		Id     *gtype.Int
		Name   *gtype.String
		Scores *gtype.Interface
	}
	s := Student{
		Id:     gtype.NewInt(1),
		Name:   gtype.NewString("john"),
		Scores: gtype.NewInterface([]int{98, 99, 100}),
	}
	json, _ := json2.Marshal(s)
	fmt.Println(string(json))

	b := []byte(`{"Id":1,"Name":"john","Scores":[100,99,98]}`)
	s1 := Student{}
	json2.Unmarshal(b, &s1)
	fmt.Println(s1)
}

func Testgqueue(r *ghttp.Request) {
	q := gqueue.New()
	// 数据生产者，每隔1秒往队列写数据
	gtimer.SetInterval(time.Second, func() {
		v := gtime.Now().String()
		q.Push(v)
		fmt.Println("Push:", v)
	})

	// 3秒后关闭队列
	gtimer.SetTimeout(3*time.Second, func() {
		q.Close()
	})

	// 消费者，不停读取队列数据并输出到终端
	for {
		if v := q.Pop(); v != nil {
			fmt.Println(" Pop:", v)
		} else {
			break
		}
	}
}

func TestQueueSelect(r *ghttp.Request) {
	queue := gqueue.New()
	// 数据生产者，每隔1秒往队列写数据
	gtimer.SetInterval(time.Second, func() {
		queue.Push(gtime.Now().String())
	})

	// 消费者，不停读取队列数据并输出到终端
	for {
		select {
		case v := <-queue.C:
			if v != nil {
				fmt.Println(v)
			} else {
				return
			}
		}
	}
}

func Testgstr(r *ghttp.Request) {
	str := "abc&\"d%$\\'''"
	res := gstr.AddSlashes(str)
	fmt.Println(res)

	str1 := "abc def"
	res1 := gstr.CamelCase(str1)
	fmt.Println(res1)

	res2 := gstr.CamelLowerCase(res1)
	fmt.Println(res2)

	str2 := 65
	fmt.Println(gstr.Chr(str2)) //A

	res3 := gstr.ChunkSplit("abcdefgh", 2, "a") //abacdaefagha
	fmt.Println(res3)

	fmt.Println(gstr.Compare("a", "a")) //0
	fmt.Println(gstr.Compare("a", "b")) //-1
	fmt.Println(gstr.Compare("b", "a")) //1

	res31 := gstr.Implode("|", g.ArrayStr{"a", "b"}) //a|b
	fmt.Println(res31)

	fmt.Println(gstr.Contains("abcd", "Ab")) //false
	fmt.Println(gstr.Contains("abcd", "ab")) //true

	fmt.Println(gstr.ContainsI("abcd", "Ab")) //true

	fmt.Println(gstr.Count("abcda", "a")) //2

	fmt.Println(gstr.CountI("abcda", "A")) //2

	fmt.Println(gstr.CountWords("abcdabab")) //

	fmt.Println(gstr.DelimitedCase("abc", 9))

	fmt.Println(gstr.Fields("abcdefg asd"))

	fmt.Println(gstr.InArray([]string{"a", "b"}, "a"))

	fmt.Println(gstr.IsNumeric("a"))  //false
	fmt.Println(gstr.IsNumeric("10")) //true

	fmt.Println(gstr.Join([]string{"a", "b"}, "|"))

	str3 := "AbcdeF"
	fmt.Println(gstr.LcFirst(str3))

	fmt.Println(gstr.NumberFormat(1234567.3456, 3, ",", "|")) //1|234|567,346

	fmt.Println(gstr.Ord("A"))

	str4 := "a=b&c=d"
	fmt.Println(gstr.Parse(str4)) //map[a:b c:d] <nil>

	fmt.Println(gstr.Pos("abcdefg", "c")) //2

	fmt.Println(gstr.Repeat("ac", 3)) //acacac

	fmt.Println(gstr.Replace("abcabcdef", "abc", "h")) //hhdef

	fmt.Println(gstr.ReplaceByArray("abcabcdef", []string{"abc", "H"})) //HHdef

	fmt.Println(gstr.ReplaceByMap("abcabcdef", map[string]string{
		"abc": "g",
	})) //ggdef

	fmt.Println(gstr.Reverse("abcdefg")) //gfedcba

	fmt.Println(gstr.RuneLen("abcdfer")) //7
	fmt.Println(gstr.RuneLen("中国"))      //2

	fmt.Println(gstr.SearchArray([]string{"a", "b", "c"}, "a")) //0
	fmt.Println(gstr.SearchArray([]string{"a", "b", "c"}, "d")) //-1

	fmt.Println(gstr.Shuffle("abcdefghi")) //ghedbicfa

	//计算两个字符串的相似度
	var a float64
	fmt.Println(gstr.SimilarText("abcdef", "abc", &a)) //3

	fmt.Println(gstr.SnakeCase("AbcDef")) //abc_def

	fmt.Println(gstr.SnakeScreamingCase("AbcDef")) //ABC_DEF

	fmt.Println(gstr.Split("abcdef_a", "_")) //[abcdef a]

	fmt.Println(gstr.SplitAndTrim("abcdefa_aca", "_", "a")) //[bcdef c]

	fmt.Println(gstr.Str("abc", "b")) //bc
	fmt.Println(gstr.Str("abc", "c")) //c

	fmt.Println(gstr.StrLimit("abc", 2, "a")) //aba

	fmt.Println(gstr.StripSlashes("abc&"))

	fmt.Println(gstr.SubStr("abcdefghi", 2, 3))  //cde
	fmt.Println(gstr.SubStr("abcdefghi", -2, 3)) //abc

	fmt.Println(gstr.ToLower("ABCDEF")) //abcdef
	fmt.Println(gstr.ToUpper("abcdef")) //ABCDEF

	fmt.Println(gstr.Trim("abcdef", "f")) //abcde

	fmt.Println(gstr.UcFirst("abcdef")) //Abcdef

	fmt.Println(gstr.UcWords("abc def")) //Abc Def
}

func Testgjson(r *ghttp.Request) {
	data :=
		`{
        "users" : {
            "count" : 100,
            "list"  : [
                {"name" : "小明",  "score" : 60},
                {"name" : "John", "score" : 99.5}
            ]
        }
    }`
	if j, err := gjson.DecodeToJson([]byte(data)); err != nil {
		glog.Error(err)
	} else {
		fmt.Println("John Score:", j.GetFloat32("users.list.1.score"))
		fmt.Println(j.GetInt("users.count"))
	}
}

func Testgjson1(r *ghttp.Request) {
	data :=
		`{
        "users" : {
            "count" : 100
        }
    }`
	if j, err := gjson.DecodeToJson([]byte(data)); err != nil {
		glog.Error(err)
	} else {
		j.Set("users.count", 2)
		j.Set("users.list", []string{"John", "小明"})
		c, _ := j.ToJson()
		fmt.Println(string(c))
	}
}

func Testgparser(r *ghttp.Request) {
	data :=
		`{
         "users" : {
                 "count" : 100,
                 "list"  : [
                     {"name" : "Ming", "score" : 60},
                     {"name" : "John", "score" : 99.5}
                 ]
         }
     }`

	if p, e := gparser.LoadContent([]byte(data)); e != nil {
		glog.Error(e)
	} else {
		fmt.Println("John Score:", p.GetFloat32("users.list.1.score"))
	}
}

func Testgparser1(r *ghttp.Request) {
	data :=
		`<?xml version="1.0" encoding="UTF-8"?>
      <note>
          <to>Tove</to>
          <from>Jani</from>
          <heading>Reminder</heading>
          <body>Don't forget me this weekend!</body>
      </note>`

	if p, e := gparser.LoadContent([]byte(data)); e != nil {
		glog.Error(e)
	} else {
		fmt.Println("Heading:", p.GetString("note.heading"))
	}
}

func Testparsesr2(r *ghttp.Request) {
	data :=
		`{
         "users" : {
             "count" : {
                 "type1" : 1,
                 "type2" : 2
             },
             "count.type1" : 100
         }
     }`
	if p, e := gparser.LoadContent([]byte(data)); e != nil {
		glog.Error(e)
	} else {
		p.SetViolenceCheck(true)
		fmt.Println("Users Count:", p.Get("users.count.type1"))
		fmt.Println("Users Count:", p.Get("users.count.type2"))
	}
}

func Testparser3(r *ghttp.Request) {
	data :=
		`{
         "users" : {
             "count" : 100
         }
     }`
	if p, e := gparser.LoadContent([]byte(data)); e != nil {
		glog.Error(e)
	} else {
		p.Set("users.count", 2)
		p.Set("users.list", []string{"John", "小明"})
		c, _ := p.ToJson()
		fmt.Println(string(c))
	}
}

func Testparser4(r *ghttp.Request) {
	data :=
		`<?xml version="1.0" encoding="UTF-8"?>
      <article>
          <count>10</count>
          <list><title>gf article1</title><content>gf content1</content></list>
          <list><title>gf article2</title><content>gf content2</content></list>
          <list><title>gf article3</title><content>gf content3</content></list>
      </article>`
	if p, e := gparser.LoadContent([]byte(data)); e != nil {
		glog.Error(e)
	} else {
		p.Remove("article.list.0")
		c, _ := p.ToJson()
		fmt.Println(string(c))
	}
}

func Testparser5(r *ghttp.Request) {
	p := gparser.New(nil)
	p.Set("name", "john")
	p.Set("age", 18)
	p.Set("scores", map[string]int{
		"语文": 100,
		"数学": 100,
		"英语": 100,
	})
	c, _ := p.ToXmlIndent("simple-xml")
	fmt.Println(string(c))

	d, _ := p.ToJsonString()
	fmt.Println(string(d))
}

func Testparser6(r *ghttp.Request) {
	type Order struct {
		Id    int     `json:"id"`
		Price float32 `json:"price"`
	}
	p := gparser.New(nil)
	p.Set("orders.list.0", Order{1, 100})
	p.Set("orders.list.1", Order{2, 666})
	p.Set("orders.list.2", Order{3, 999.99})
	fmt.Println("Order 1 Price:", p.Get("orders.list.1.price"))
	c, _ := p.ToJson()
	fmt.Println(string(c))
}

//将map转为结构体
func Testparser7(r *ghttp.Request) {
	type Info struct {
		Name string
		Url  string
	}
	o := Info{}
	p := gparser.New(map[string]string{
		"Name": "gf",
		"Url":  "https://gitee.com/johng",
	})
	p.ToStruct(&o)
	fmt.Println("Name:", o.Name)
	fmt.Println("Url :", o.Url)
}

func Test_gbase64(r *ghttp.Request) {
	res := gbase64.Encode([]byte("base64"))
	fmt.Println(string(res))

	res1, _ := gbase64.Decode(res)
	fmt.Println(string(res1))

	a := gbase64.EncodeString("foo")
	fmt.Println(a)

	b, _ := gbase64.DecodeString(a)
	fmt.Println(string(b))
}

//类似于php的hash_hmac('sha256', $param, $appkey)
func Test_hash_hmac(r *ghttp.Request) {
	secret := "mysecret"
	data := "data"
	fmt.Printf("Secret: %s Data: %s\n", secret, data)

	// Create a new HMAC by defining the hash type and the key (as byte array)
	h := hmac.New(sha256.New, []byte(secret))

	// Write Data to it
	h.Write([]byte(data))

	// Get result and encode as hexadecimal string
	sha := hex.EncodeToString(h.Sum(nil))

	fmt.Println("Result: " + sha)
}

func Test_gtime(r *ghttp.Request) {
	t := gtime.Now()
	res := t.Format("Y-m-d H:i:s.u")
	fmt.Println(res) //2020-02-11 12:52:49.887

	fmt.Println(gtime.Now()) //2020-02-11 12:53:25

	fmt.Println(gtime.Datetime()) //2020-02-11 12:54:17

	fmt.Println(gtime.Date()) //2020-02-11

	fmt.Println(gtime.Timestamp()) //1581396934

	fmt.Println(gtime.StrToTime("2020-02-10 09:30:00", "Y-m-d H:i:s"))

	fmt.Println(gtime.NewFromStrFormat("2020-02-11 09:30:00", "Y-m-d"))

	// 去年今日
	fmt.Println(gtime.Now().AddDate(-1, 0, 0).Format("Y-m-d"))

	// 去年今日，UTC时间
	fmt.Println(gtime.Now().AddDate(-1, 0, 0).Format("Y-m-d H:i:s T"))
	fmt.Println(gtime.Now().AddDate(-1, 0, 0).UTC().Format("Y-m-d H:i:s T"))

	// 下个月1号凌晨0点整
	fmt.Println(gtime.Now().AddDate(0, 1, 0).Format("Y-m-d 00:00:00"))

	// 1个小时前
	fmt.Println(gtime.Now().Add(-time.Hour).Format("Y-m-d H:i:s"))

	d := gtime.NewFromStr("2020-02-10 09:30:00")
	fmt.Println(d.AddDate(-1, 0, 0).Format("Y-m-d H:i:s"))
}

func Test_gmutex(r *ghttp.Request) {
	mu := gmutex.New()
	for i := 0; i < 10; i++ {
		go func(n int) {
			mu.Lock()
			defer mu.Unlock()
			glog.Println("Lock:", n)
			time.Sleep(time.Second)
		}(i)
	}
	for i := 0; i < 10; i++ {
		go func(n int) {
			mu.RLock()
			defer mu.RUnlock()
			glog.Println("RLock:", n)
			time.Sleep(time.Second)
		}(i)
	}
	time.Sleep(11 * time.Second)
}

func Test_gproc(r *ghttp.Request) {
	res, _ := gproc.ShellExec(`sleep 3s; echo "hello gf!";`)
	fmt.Println("result:", res)
}

func Test_gproc1(r *ghttp.Request) {
	if gproc.IsChild() {
		glog.Printf("%d: Hi, I am child, waiting 3 seconds to die", gproc.Pid())
		time.Sleep(time.Second)
		glog.Printf("%d: 1", gproc.Pid())
		time.Sleep(time.Second)
		glog.Printf("%d: 2", gproc.Pid())
		time.Sleep(time.Second)
		glog.Printf("%d: 3", gproc.Pid())
	} else {
		m := gproc.NewManager()
		p := m.NewProcess(os.Args[0], os.Args, os.Environ())
		p.Start()
		p.Wait()
		glog.Printf("%d: child died", gproc.Pid())
	}
}

func job() {
	time.Sleep(1 * time.Second)
}

func Test_grpool(r *ghttp.Request) {
	pool := grpool.New(100)
	for i := 0; i < 1000; i++ {
		pool.Add(job)
	}
	fmt.Println("worker:", pool.Size())
	fmt.Println("  jobs:", pool.Jobs())
	gtimer.SetInterval(time.Second, func() {
		fmt.Println("worker:", pool.Size())
		fmt.Println("  jobs:", pool.Jobs())
		fmt.Println()
	})

	select {}
}

func Test_gmd5(r *ghttp.Request) {
	res, _ := gmd5.Encrypt("foo")
	fmt.Println(res)

}

func Test_gconv(r *ghttp.Request) {
	a := "12asda"
	b := gconv.Bytes(a)
	fmt.Println(b)

	fmt.Println(gconv.String(b))

	fmt.Println(gconv.Time("2020-02-11"))
}

func Test_grand(r *ghttp.Request) {
	fmt.Println(grand.Digits(10)) //返回长度为10的都是数字的随机字符串

	fmt.Println(grand.Intn(100)) //返回0-100的随机数

	fmt.Println(grand.Letters(20))
}

func Test_guuid(r *ghttp.Request) {
	uuid := guuid.New()
	fmt.Println(uuid)

	fmt.Println(guuid.NewDCEGroup())

	fmt.Println(guuid.NewDCEPerson())

	fmt.Println(guuid.NewMD5(uuid, gconv.Bytes("foo")))

	fmt.Println(guuid.NewRandom())

	Test1("foo", "bar", 1)
}

func Test1(where ...interface{}) {
	fmt.Println(where)
}

func Test_page(r *ghttp.Request) {
	page := gconv.Int(r.GetRequest("page", 1))
	perPage := gconv.Int(r.GetInt("per_page", 10))

	model := g.DB().Table("user").Where("id > ?", 1).Order("id desc")
	pageData, err := page_lib.GetPage(model, page, perPage)
	if err != nil {
		resp.Error(r, err.Error())
	}
	resp.Succ(r, pageData)
}

func Test_getpage(r *ghttp.Request) {
	page := gconv.Int(r.GetRequest("page", 1))
	perPage := gconv.Int(r.GetInt("per_page", 10))

	pageData := user.GetPageData(page, perPage)
	resp.Succ(r, pageData)
}

func MakeNewSalt(salt string) (string) {
	if salt == "" || len(salt) == 0 {
		return ""
	}

	key := "gTx9bi1#NQ7b%yKY"
	uLen := len(salt)
	var res, c string
	for i := 0; i < uLen; i++ {
		for j := 0; j < 16; j++ {
			c = gstr.Chr(gconv.Int(salt[i]) ^ gconv.Int(key[j]))
			res += gconv.String(c)
		}
	}
	if len(res) > 16 {
		res = res[0:16]
	}
	res = gstr.TrimRight(res)
	return res
}

func MakeNewPasswd(r *ghttp.Request) {
	user := "yuanlj"
	pwd := "123"

	newSalt := MakeNewSalt(user)
	new := fmt.Sprintf("%s%s", pwd, newSalt)
	newPasswd := Sha256Encode(new)
	fmt.Println(newPasswd)
}

func Sha256Encode(str string) string {
	res := sha256.Sum256(gconv.Bytes(str))
	data := fmt.Sprintf("%x", res)
	return data
}

func TestUploadFile(r *ghttp.Request){

}
